package com.wlts.wzy.KSOrderModule.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.linkedmall.model.v20180116.*;
import com.wlts.wzy.Base.BaseEntity;
import com.wlts.wzy.KSOrderModule.entity.KsOrders;
import com.wlts.wzy.KSOrderModule.service.IKsOrdersService;
import com.wlts.wzy.LMGoodsModule.entity.LmAddress;
import com.wlts.wzy.LMGoodsModule.entity.LmSelfGoods;
import com.wlts.wzy.LMGoodsModule.service.ILmAddressService;
import com.wlts.wzy.LMGoodsModule.service.ILmSelfGoodsService;
import com.wlts.wzy.Result.Result;
import com.wlts.wzy.api.request.ks.IdsRequest;
import com.wlts.wzy.api.vo.DeliveryAddress;
import com.wlts.wzy.api.vo.KsVO.KsOrdersAddress;
import com.wlts.wzy.api.vo.KsVO.KsOrdersGoodsVO;
import com.wlts.wzy.configBean.LmConfig.LmConfig;
import com.wlts.wzy.expand.MyLambdaQueryWrapper;
import com.wlts.wzy.util.AddressResolutionUtil;
import com.wlts.wzy.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.wlts.wzy.configBean.LmConfig.LmConfig.client;

@Component
public class PutOrdersToLmUtil {
    @Autowired
    private IKsOrdersService ksOrdersService;
    @Autowired
    private ILmSelfGoodsService lmSelfGoodsService;
    @Autowired
    private ILmAddressService lmAddressService;


    /**
     * 判断是否平台订单
     */
    @Scheduled(fixedDelay = 222 * 1000)
    public void checkPTOrders() {



        MyLambdaQueryWrapper<KsOrders> queryWrapper = new MyLambdaQueryWrapper<>();

        queryWrapper.in(KsOrders::getSelfOrder, 0);//平台商品的订单 0未确定 1是 2不是

        List<KsOrders> ksOrdersList = ksOrdersService.list(queryWrapper);

        ksOrdersList.forEach(ksOrders -> {
            List<KsOrdersGoodsVO> ksOrdersGoodsVOList = JSON.parseArray(ksOrders.getOrderProductInfoList(), KsOrdersGoodsVO.class);
            if (ksOrdersGoodsVOList.size() > 0) {

                KsOrdersGoodsVO ksOrdersGoods = ksOrdersGoodsVOList.get(0);

                MyLambdaQueryWrapper<LmSelfGoods> selfGoodsWrapper = new MyLambdaQueryWrapper<>();

                selfGoodsWrapper.eq(LmSelfGoods::getRelItemId, ksOrdersGoods.getRelItemId());

                LmSelfGoods lmSelfGoods = lmSelfGoodsService.getOne(selfGoodsWrapper);

                if (lmSelfGoods == null) {
                    ksOrders.setSelfOrder(2);//如果商品不存在，证明不是平台推送的商品
                    ksOrdersService.updateById(ksOrders);
                } else {
                    ksOrders.setSelfOrder(1);
                    ksOrdersService.updateById(ksOrders);
                }
            }
        });
    }


    /**
     * 将快手订单推送到lm库
     */
   // @Scheduled(fixedDelay = 777 * 1000)
//    @PostConstruct
    public void putOrderToLm() {

        MyLambdaQueryWrapper<KsOrders> queryWrapper = new MyLambdaQueryWrapper<>();

        queryWrapper.in(KsOrders::getSelfOrder, 1);//平台商品的订单 0未确定 1是 2不是

        queryWrapper.eq(KsOrders::getPutLmStatus, 1);//推送lm状态 0未推送 1已推送 2推送失败

        queryWrapper.like(KsOrders::getOrderProductInfoList, "\"num\":2,");//推送lm状态 0未推送 1已推送 2推送失败

        queryWrapper.eq(KsOrders::getStatus, 40);//订单状态：[0, \"未知状态\"], [10, \"待付款\"], [30, \"已付款\"], [40, \"已发货\"], [50, \"已签收\"], [70, \"订单成功\"], [80, \"订单失败\"]



        List<KsOrders> ordersList = ksOrdersService.list(queryWrapper);

        System.out.println("推送订单的数量："+ordersList.size());


        System.out.println("开始推送："+ordersList.size());

//        List<Long> fileSelfOrder = new ArrayList<>();
//        List<Long> PutLmStatus = new ArrayList<>();
//        List<Long> getStatus = new ArrayList<>();
//
//
//        ordersList.forEach(ksOrders -> {
//
//            if (ksOrders.getSelfOrder() != 1) {
//                fileSelfOrder.add(ksOrders.getOid());
//            }
//            if (ksOrders.getPutLmStatus() != 0 && ksOrders.getPutLmStatus() != 2) {
//                PutLmStatus.add(ksOrders.getOid());
//            }
//            if (ksOrders.getStatus() != 30) {
//                getStatus.add(ksOrders.getOid());
//            }
//
//        });




        List<String> failOrder = new ArrayList<>();
        JSONArray jsonArray=new JSONArray();
        ordersList.forEach(ksOrders -> {

            JSONObject jsonObject=new JSONObject();

            String oid=ksOrders.getOid()+"";

            oid=oid.substring(0, oid.length() -1);

            jsonObject.put("oid",ksOrders.getOid());
            jsonObject.put("replaceId",oid);

            List<KsOrdersGoodsVO> ksOrdersGoodsVOList = JSON.parseArray(ksOrders.getOrderProductInfoList(), KsOrdersGoodsVO.class);

//[{"buyerId":0,"createTime":1612605117278,"discountFee":0,"id":8283462433580,"itemId":943491185290,"itemLinkUrl":"https://app.kwaixiaodian.com/merchant/shop/detail?id=943491185290&hyId=kwaishop&layoutType=4","itemPicUrl":"https://ali-ec.static.yximgs.com/ufile/adsocial/87243885-9d23-45e8-bd5d-d15dac7df6c0.jpg","itemTitle":"【瑜大直播】艺品赞红豆薏米茶150g*1袋","itemType":1,"num":1,"oid":2103700006986580,"originalPrice":990,"price":990,"refundId":2103700007004580,"refundList":[{"refundId":2103700007004580,"refundStatus":10}],"refundStatus":10,"relItemId":1612577579226,"relSkuId":0,"skuDesc":"红豆薏米茶","skuId":943491186290,"updateTime":1612605117278}]

            if (ksOrdersGoodsVOList.size() > 0) {

                KsOrdersGoodsVO ksOrdersGoods = ksOrdersGoodsVOList.get(0);

                MyLambdaQueryWrapper<LmSelfGoods> selfGoodsWrapper = new MyLambdaQueryWrapper<>();

                selfGoodsWrapper.eq(LmSelfGoods::getRelItemId, ksOrdersGoods.getRelItemId());

                LmSelfGoods lmSelfGoods = lmSelfGoodsService.getOne(selfGoodsWrapper);

                if (lmSelfGoods != null) {
                    //    if(ksOrders.getStatus()==30){
                    CreateOrderV2Request request = new CreateOrderV2Request();
                    CreateOrderV2Request.ItemList itemList = new CreateOrderV2Request.ItemList();
                    DeliveryAddress deliveryAddress = new DeliveryAddress();
                    request.setBizId(LmConfig.LZ_BIZ_ID);
                    request.setAccountType("ANONY");
                    request.setThirdPartyUserId(ksOrders.getSellerId() + "");
                    request.setBizUid(request.getThirdPartyUserId());

                    List<CreateOrderV2Request.ItemList> itemLists = new ArrayList<>();

                    request.setOutTradeId(oid + "");

                    itemList.setLmItemId(lmSelfGoods.getLmItemId() + "");

                    itemList.setQuantity((int)ksOrdersGoods.getNum());

                    if (ksOrdersGoods.getRelSkuId() != 0) {
                        itemList.setSkuId(ksOrdersGoods.getRelSkuId());
                    } else {
                        if (ksOrdersGoods.getSkuNick() != null) {
                            itemList.setSkuId(Long.valueOf(ksOrdersGoods.getSkuNick()));
                        }
                    }


                    KsOrdersAddress ksOrdersAddress = JSONObject.parseObject(ksOrders.getAddress(), KsOrdersAddress.class);

                    /**
                     * 设置地址
                     */
                    deliveryAddress.setFullName(ksOrdersAddress.getConsignee());
                    deliveryAddress.setMobile(ksOrdersAddress.getMobile());
                    deliveryAddress.setAddressDetail(ksOrdersAddress.getProvince() + ksOrdersAddress.getCity() + ksOrdersAddress.getDistrict() + ksOrdersAddress.getAddress());

                    MyLambdaQueryWrapper<LmAddress> provinceWrapper = new MyLambdaQueryWrapper<>();

                    provinceWrapper.like(LmAddress::getDivisionName, ksOrdersAddress.getProvince());

                    provinceWrapper.eq(LmAddress::getParentId, 1);

                    LmAddress province = lmAddressService.getOne(provinceWrapper);

                    if (province == null) {
                        MyLambdaQueryWrapper<LmAddress> provinceWrapper2 = new MyLambdaQueryWrapper<>();

                        provinceWrapper2.like(LmAddress::getDivisionName, ksOrdersAddress.getProvince().replace("市", ""));

                        provinceWrapper2.eq(LmAddress::getParentId, 1);
                        province = lmAddressService.getOne(provinceWrapper2);
                    }

                    if (province != null) {
                        MyLambdaQueryWrapper<LmAddress> cityWrapper = new MyLambdaQueryWrapper<>();

                        cityWrapper.like(LmAddress::getDivisionName, ksOrdersAddress.getCity());

                        cityWrapper.eq(LmAddress::getParentId, province.getDivisionCode());

                        LmAddress city = lmAddressService.getOne(cityWrapper);

                        boolean jump = false;

                        if (city == null) {
                            if (ksOrdersAddress.getCity().equals("市辖区") || ksOrdersAddress.getCity().equals("县")) {

                                MyLambdaQueryWrapper<LmAddress> cityWrapper1 = new MyLambdaQueryWrapper<>();

                                cityWrapper1.like(LmAddress::getDivisionName, ksOrdersAddress.getProvince());

                                cityWrapper1.eq(LmAddress::getParentId, province.getDivisionCode());

                                city = lmAddressService.getOne(cityWrapper1);
                            } else {
                                if (ksOrdersAddress.getCity().equals("自治区直辖县级行政区划") || ksOrdersAddress.getCity().equals("省直辖县级行政区划")) {
                                    jump = true;
                                }
                            }
                        }
                        if (city == null && !jump) {
                            System.out.println(ksOrders.getAddress());
                            System.out.println("系统不存在" + ksOrdersAddress.getProvince() + "省下的：" + ksOrdersAddress.getCity());
                        } else {
                            LmAddress dest;
                            if (jump) {
                                MyLambdaQueryWrapper<LmAddress> destWrapper = new MyLambdaQueryWrapper<>();

                                destWrapper.like(LmAddress::getDivisionName, ksOrdersAddress.getDistrict());

                                destWrapper.eq(LmAddress::getParentId, province.getDivisionCode());

                                dest = lmAddressService.getOne(destWrapper);
                            } else {
                                MyLambdaQueryWrapper<LmAddress> destWrapper = new MyLambdaQueryWrapper<>();

                                destWrapper.like(LmAddress::getDivisionName, ksOrdersAddress.getDistrict());

                                destWrapper.eq(LmAddress::getParentId, city.getDivisionCode());

                                dest = lmAddressService.getOne(destWrapper);
                            }

                            if (dest == null) {

                                if (jump) {
                                    MyLambdaQueryWrapper<LmAddress> destWrapper1 = new MyLambdaQueryWrapper<>();

                                    destWrapper1.like(LmAddress::getDivisionName, "其它区");

                                    destWrapper1.eq(LmAddress::getParentId, province.getDivisionCode());

                                    dest = lmAddressService.getOne(destWrapper1);
                                } else {
                                    MyLambdaQueryWrapper<LmAddress> destWrapper1 = new MyLambdaQueryWrapper<>();

                                    destWrapper1.like(LmAddress::getDivisionName, "其它区");

                                    destWrapper1.eq(LmAddress::getParentId, city.getDivisionCode());

                                    dest = lmAddressService.getOne(destWrapper1);
                                }

                                if (dest == null) {
                                    System.out.println("系统不存在" + ksOrdersAddress.getProvince() + "省下：" + ksOrdersAddress.getCity() + "市的区：" + ksOrdersAddress.getDistrict());
                                }


                            }

                            if (dest != null) {

                                deliveryAddress.setDivisionCode(dest.getDivisionCode() + "");

                                List<Map<String, String>> table = AddressResolutionUtil.addressResolution(ksOrdersAddress.getAddress());

                                if (table.size() > 0) {

                                    String townName = table.get(0).get("town");

                                    if (!StringUtils.isEmpty(townName)) {

                                        //    System.out.println("街道名字："+townName);

                                        MyLambdaQueryWrapper<LmAddress> townWrapper = new MyLambdaQueryWrapper<>();

                                        townWrapper.like(LmAddress::getDivisionName, townName);

                                        townWrapper.eq(LmAddress::getParentId, dest.getDivisionCode());

                                        LmAddress town = lmAddressService.getOne(townWrapper);

                                        if (town != null) {
                                            //    System.out.println("街道："+town.toString());
                                            deliveryAddress.setTownDivisionCode(town.getDivisionCode() + "");
                                        }
                                    }
                                }

                                itemLists.add(itemList);

                                request.setItemLists(itemLists);

                                //    System.out.println("地址详细："+JSON.toJSONString(deliveryAddress));

                                request.setDeliveryAddress(JSON.toJSONString(deliveryAddress));

                                try {
                                    //    System.out.println("请求内容："+JSON.toJSONString(request));
                                    //创建订单
                                    CreateOrderV2Response resp = client.getAcsResponse(request);
                                    System.out.println("正在推送");
                                    System.out.println("报文内容：" + JSON.toJSONString(resp.getMessage()));


                                    if (resp.getCode().equals("SUCCESS")) {

//                                        ksOrders.setLmOrderId(resp.getModel().getLmOrderList().get(0).getLmOrderId());
//                                        ksOrders.setTbOrderId(resp.getModel().getOrderIds().get(0));
                                        jsonObject.put("lmOrderId",resp.getModel().getLmOrderList().get(0).getLmOrderId());
                                        jsonObject.put("TbOrderId",resp.getModel().getOrderIds().get(0));

                                        jsonArray.add(jsonObject);

                                        ksOrders.setRemarks(jsonObject.toJSONString());

                                        EnableOrderResponse enableOrderResponse = enableOrder(request.getOutTradeId(), resp.getModel().getLmOrderList().get(0).getLmOrderId(), ksOrders.getSellerId() + "");

                                        if (enableOrderResponse.getCode().equals("SUCCESS")) {
                                            //ksOrders.setPutLmStatus(1);
                                        } else {
                                          //  ksOrders.setPutLmStatus(2);
                                            failOrder.add(ksOrders.getOid() + "");
                                        }

                                       // ksOrders.setLmErrMsg(JSON.toJSONString(enableOrderResponse));
                                    } else {
                                        failOrder.add(ksOrders.getOid() + "");
                                        if (!resp.getCode().equals("CALL_TRADE_SRVICE_FAIL")) {
                                         //   ksOrders.setPutLmStatus(2);
                                            ksOrders.setLmErrMsg(JSON.toJSONString(resp));
                                        } else {
                                            System.out.println("跳过保存");
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                ksOrdersService.updateById(ksOrders);
                            } else {
                            //    ksOrders.setPutLmStatus(2);
                                ksOrders.setLmErrMsg("{\"code\":\"NO_ADDRESS\",\"logsId\":\"\",\"message\":\"无对应地址\",\"model\":{\"lmOrderList\":[],\"orderIds\":[],\"payTradeIds\":[],\"redirectUrl\":\"\"},\"requestId\":\"120F7222-4C88-4FC5-BD7E-3A9B3557F32D\",\"subCode\":\"\",\"subMessage\":\"\",\"success\":true}");
                                ksOrdersService.updateById(ksOrders);
                            }
                        }
                    } else {
                        System.out.println("系统不存在省份：" + ksOrdersAddress.getProvince());
                    }
                }
            }
        });
        if (failOrder.size() > 0) {
           System.out.println("推送失败订单："+JSON.toJSONString(failOrder));
        }

        System.out.println(jsonArray.toString());

    }


    /**
     * 确定收货
     */
    @Scheduled(fixedDelay = 333 * 1000)
//    @PostConstruct
    public void confirmOrder() {

        MyLambdaQueryWrapper<KsOrders> queryWrapper = new MyLambdaQueryWrapper<>();

        queryWrapper.in(KsOrders::getSelfOrder, 1);//平台商品的订单 0未确定 1是 2不是

        queryWrapper.eq(KsOrders::getPutLmStatus, 1);//推送lm状态 0未推送 1已推送 2推送失败

        queryWrapper.eq(KsOrders::getStatus, 50);//订单状态：[0, \"未知状态\"], [10, \"待付款\"], [30, \"已付款\"], [40, \"已发货\"], [50, \"已签收\"], [70, \"订单成功\"], [80, \"订单失败\"]

        queryWrapper.isNotNull(KsOrders::getLmOrderId);

        List<KsOrders> ksOrdersList = ksOrdersService.list(queryWrapper);

        ksOrdersList.forEach(ksOrders -> {

            ConfirmDisburseRequest request = new ConfirmDisburseRequest();
            request.setBizId(LmConfig.LZ_BIZ_ID);
            request.setAccountType("ANONY");
            request.setThirdPartyUserId(ksOrders.getSellerId() + "");
            request.setBizUid(request.getThirdPartyUserId());
            request.setLmOrderId(ksOrders.getLmOrderId());

            try {
                ConfirmDisburseResponse resp = client.getAcsResponse(request);
                if (resp.getCode().equals("SUCCESS")) {
                    ksOrders.setPutLmConfirmStatus(1);
                } else {
                    ksOrders.setPutLmConfirmStatus(2);
                }
                ksOrders.setLmErrMsg(JSON.toJSONString(resp));
            } catch (ClientException e) {
                e.printStackTrace();
                ksOrders.setPutLmConfirmStatus(2);
                ksOrders.setLmErrMsg(e.getMessage());
            }
        });

        if (ksOrdersList.size() > 0) {
            ksOrdersService.updateBatchById(ksOrdersList);
        }


    }


    /**
     * 支付订单
     *
     * @return
     */
    public static EnableOrderResponse enableOrder(String outOrderId, String lmOrderId, String sellerId) throws ClientException {

        //{"code":"SUCCESS","logsId":"","message":"操作成功，但是创建支付单失败，请到订单列表点击继续支付。","model":{"lmOrderList":[{"lmOrderId":"243467676"}],"orderIds":["1541205903044906332"],"payTradeIds":[],"redirectUrl":"https://pages.tmall.com/wow/wt/act/lm-pages?wh_page=order-list"},"requestId":"0B2A116C-BD1A-4467-B68C-4783D163F0A8","subCode":"","subMessage":"","success":true}
        EnableOrderRequest request = new EnableOrderRequest();
        request.setBizId(LmConfig.LZ_BIZ_ID);
        request.setOutTradeId(outOrderId);
        request.setAccountType("ANONY");
        request.setThirdPartyUserId(sellerId);
        request.setBizUid(request.getThirdPartyUserId());
        request.setLmOrderId(lmOrderId);


        EnableOrderResponse resp = client.getAcsResponse(request);

        //  System.out.println(JSON.toJSONString(resp));

        //{"code":"WITHHOLD_RESULT_STATUS_UNKOWN","logsId":"","message":"RESULT_STATUS_UNKOWN","model":{"lmOrderList":[],"orderIds":[],"payTradeIds":[],"redirectUrl":"RESULT_STATUS_UNKOWN"},"requestId":"B1AC36AC-903D-47EB-839A-A7AA442979A4","subCode":"","subMessage":"","success":true}
        return resp;


    }

}
